package com.dy.yunying.biz.controller.yyz;

import com.dy.yunying.api.base.BaseDto;
import com.dy.yunying.api.enums.RedisNameEnum;
import com.dy.yunying.api.req.yyz.MsgReq;
import com.dy.yunying.biz.utils.SCaptcha;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: kyf
 * @Date: 2020/12/10 16:13
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/captchas")
@Inner(value = false)
public class CaptchaImageController {
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@RequestMapping(value = "/random", method = RequestMethod.GET)
	public R sendSms() {
		String random = UUID.randomUUID().toString().replaceAll("-", "");
		redisTemplate.opsForValue().set(RedisNameEnum.RANDOM_KEY.get(random), random, 30, TimeUnit.MINUTES);
		return R.ok(random);
	}


	@RequestMapping(value = "/image", method = RequestMethod.GET)
	public void image(HttpServletRequest req, HttpServletResponse resp) {
		log.info(" get captcha image begin");
		try {
			resp.setContentType("image/jpeg");
			// 禁止图像缓存。
			resp.setHeader("Pragma", "no-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", 0);

			ServletOutputStream out = resp.getOutputStream();
			String code = req.getParameter("codeType");
			String random = req.getParameter("random");
			//1:参数检查
			if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(random)) {
				String randomKey = redisTemplate.opsForValue().get(RedisNameEnum.RANDOM_KEY.get(random));
				if (StringUtils.isBlank(randomKey)) {
					log.info("随机码错误或者不存在；返回空白图片");
					setBlankImage(out);
				} else {
					Integer codeType = Integer.valueOf(code);
					String captcha = redisTemplate.opsForValue().get(RedisNameEnum.SCAPTCHA_KEY.get(codeType) + "_" + random);
					if (StringUtils.isNotBlank(captcha)) {
						//移除之前的验证码缓存
						redisTemplate.delete(RedisNameEnum.SCAPTCHA_KEY.get(codeType) + "_" + random);
					}
					SCaptcha instance = new SCaptcha(93, 38, Color.WHITE);
					redisTemplate.opsForValue().set(RedisNameEnum.SCAPTCHA_KEY.get(codeType) + "_" + random, instance.getCode(), 480, TimeUnit.SECONDS);
					log.info("生成的图形验证码：" + instance.getCode() + ",redis中的图形验证码:" + RedisNameEnum.SCAPTCHA_KEY.get(codeType) + "_" + random);
					instance.write(out);
				}
			} else {
				log.info("生成的图形验证码：参数为空；返回空白图片");
				setBlankImage(out);
			}
		} catch (Exception e) {
			log.error("生成的图形验证码：失败");
			log.error(e.getMessage(), e);
		}
		log.info("get captcha image end");
	}

	/***
	 * 设置空白图片
	 * @param out
	 * @throws IOException
	 */
	private void setBlankImage(ServletOutputStream out) throws IOException {
		BufferedImage buffImg = new BufferedImage(93, 38, BufferedImage.TYPE_INT_RGB);
		buffImg.getGraphics().setColor(new Color(60, 58, 82));
		ImageIO.write(buffImg, "png", out);
		out.close();
	}

}
